using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Lesson1 : MonoBehaviour
{
    public Image image;
    // Start is called before the first frame update
    void Start()
    {
        //第一步 加载AB包(AB包不能重复加载,否则会报错)
        AssetBundle ab = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/" + "model");

        //第二步 加载AB包中的资源
        //只是用名字加载 会出现 同名不同类型资源 分不清
        //建议使用 泛型加载 或者是 Type指定类型
        //方式一
        GameObject obj = ab.LoadAsset<GameObject>("Cube");
        //方式二(Lua中不支持泛型，只能使用这种加载方式)
        //GameObject obj = ab.LoadAsset("Cube", typeof(GameObject)) as GameObject;
        Instantiate(obj);
        //加载一个圆
        GameObject obj2 = ab.LoadAsset<GameObject>("Sphere");
        Instantiate(obj2);

        //异步加载->协程
        StartCoroutine(LoadABRes("login", "ui_TY_gouxuan_01"));

        //卸载单个AB包(参数为true 会把通过AB包加载的资源也卸载了)
        ab.Unload(false);
    }

    IEnumerator LoadABRes(string ABName, string resName)
    {
        //第一步 加载AB包
        AssetBundleCreateRequest abcr = AssetBundle.LoadFromFileAsync(Application.streamingAssetsPath + "/" + ABName);
        yield return abcr;

        //第二步 加载资源
        AssetBundleRequest abq = abcr.assetBundle.LoadAssetAsync(resName, typeof(Sprite));
        yield return abq;
        image.sprite = abq.asset as Sprite;
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            Debug.LogFormat("卸载所有加载的AB包,关联资源也卸载.");
            //卸载所有加载的AB包(参数为true 会把通过AB包加载的资源也卸载了)
            AssetBundle.UnloadAllAssetBundles(true);
        }
        if (Input.GetKeyDown(KeyCode.B))
        {
            Debug.LogFormat("卸载所有加载的AB包.");
            AssetBundle.UnloadAllAssetBundles(false);
        }
    }
}